﻿using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using JTTD.Domain.Dtos;
using JTTD.Domain.Dtos.Account.Response;
using JTTD.Domain.Units;
using JTTD.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace JTTD.Controllers
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    [ApiController]
    [Produces("application/json")]
    [TypeFilter(typeof(AuthorizeTokenFilter))]
    [TypeFilter(typeof(DtoValidFilte))]
    public class BaseController : ControllerBase
    {
        /// <summary>
        /// 用户id
        /// </summary>
        protected int UserId => HttpContext.Session.GetInt32(ApiConsts.UserIdKey) ?? 0;

        /// <summary>
        /// 用户类型 0、手机用户 1、管理员，2、商户
        /// </summary>
        protected int UserType => HttpContext.Session.GetInt32(ApiConsts.UserType) ?? 0;
       

        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="account"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        protected async Task<ApiResult<string>> GetIdentityToken(AccountResponseDto account, IConfiguration configuration)
        {
            var client = new HttpClient();
            var applicationUrl = configuration["AppSetting:ApplicationUrl"];
            var disco = await client.GetDiscoveryDocumentAsync(applicationUrl);
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,
                GrantType = "password",
                UserName = account.UserId.ToString(),
                Password= account.UserType.ToString(),
                ClientId = "jttdClient",
                ClientSecret = "jttdSecret",
                Scope= "jttdApi"
            });
            if (tokenResponse.IsError)
            {
                return ApiResultUnit.Error<string>(tokenResponse.Error);
            }
            else
            {
                var token = tokenResponse.Json["token_type"] + " " + tokenResponse.Json["access_token"].ToString();
                return ApiResultUnit.Success(token);
            }
        }

    }
}
